package com.nuanshui.heatedloan.baseservice.service;

import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.utils.redis.JedisUtil;
import com.nuanshui.heatedloan.baseservice.dal.mapper.ActionCountMapper;
import com.nuanshui.heatedloan.baseservice.facade.ActionCountService;
import com.nuanshui.heatedloan.baseservice.model.ActionCount;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service(ServiceConstant.ACTIONCOUNTSERVICE)
@Transactional(readOnly=true,  value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
public class ActionCountServiceImpl  extends CommonServiceImpl implements ActionCountService{

	@Autowired
	private ActionCountMapper actionCountMapper;
	@Autowired
	private JedisUtil jedisUtil;
	
	@Override
	@Transactional(value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public void incrCount(String bizId, int type) {
		synchronized (ActionCountServiceImpl.class) {
			actionCountMapper.incrCount(bizId, type);
		}
	}

	@Override
	@Transactional(value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public void save(ActionCount actionCount) {
		actionCountMapper.save(actionCount);
		
	}

	@Override
	@Transactional(value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public void decrCount(String bizId, int type) {
		synchronized (ActionCountServiceImpl.class) {
			actionCountMapper.decrCount(bizId, type);	
		}		
	}

	@Override
	public Long getCount(String bizId, int type) {
		
		return actionCountMapper.getCount(bizId, type);
	}

	@Override
	@Transactional(readOnly=false,value=TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public void updateCount(Long count, String bizId, int type) {
		   String id = "COUNT_"+type+"_"+bizId;
		   String  countStr = jedisUtil.get(id);
		   if(SysStringUtils.isNotEmpty(countStr) && !"null".equals(countStr)) {
			   Long c = Long.parseLong(countStr);
			   if(c == count) return;
		   }
           actionCountMapper.updateCount(count, bizId, type);	
          
           jedisUtil.set(id,count+"");
	}

}
